package com.zqweb.gulimall.cart.interceptor;

import com.zqweb.common.constant.AuthServerConstant;
import com.zqweb.common.constant.CartConstant;
import com.zqweb.common.vo.MemberUserInfoVo;
import com.zqweb.gulimall.cart.vo.CartUserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


public class Cart_UserCheckInterceptor implements HandlerInterceptor {
    // 新建1个值类型为CartUserInfoTo类的ThreadLocal实例，用于同个线程的数据共享
    public static ThreadLocal<CartUserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    // 请求到达处理器之前：进行拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("进入拦截器，开始预拦截...");
        CartUserInfoTo cartUserInfoTo = new CartUserInfoTo();
        // 判断userId
        HttpSession session = request.getSession();
        MemberUserInfoVo memberUserInfoVo = (MemberUserInfoVo) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        if(memberUserInfoVo != null){
            cartUserInfoTo.setUserId(memberUserInfoVo.getId());
        }
        // 判断user-key这个cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if(CartConstant.TEMP_USER_COOKIE_NAME.equals(cookieName)){
                    // 浏览器端存在user-key这个cookie：设置userKey和hasUserKeyCookie
                    cartUserInfoTo.setUserKey(cookie.getValue());
                    cartUserInfoTo.setHasUserKeyCookie(true);
                }
            }
        }
        // 没有user-key这个cookie，则随机赋个UUID
        if(StringUtils.isEmpty(cartUserInfoTo.getUserKey())){
           cartUserInfoTo.setUserKey(UUID.randomUUID().toString());
        }
        // 将设置好userId和userKey的cartUserInfoTo设置到ThreadLocal实例中
        threadLocal.set(cartUserInfoTo);

        return true;// 放行拦截的请求
    }

    @Override
    // 请求经处理器处理完毕后：进行拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("返回响应给浏览器之前的拦截处理...");
        CartUserInfoTo cartUserInfoTo = threadLocal.get();
        // 判断是否存在user-key的cookie，没有就新建1个：无论是已登陆还是未登陆的用户，然后存储到浏览器端
        if(!cartUserInfoTo.isHasUserKeyCookie()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, cartUserInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);// 30天对应的秒数
            response.addCookie(cookie);
        }
    }
}
